/* eslint-disable react-native/no-inline-styles */
import React, {Component} from 'react';
import {Input, Button, CheckBox} from 'react-native-elements';
import {
  View,
  StatusBar,
  SafeAreaView,
  ScrollView,
  Image,
  StyleSheet,
  BackHandler,
  ToastAndroid,
  Platform,
  Keyboard,
} from 'react-native';
import {NavigationActions, StackActions} from 'react-navigation';
import Icon from 'react-native-vector-icons/FontAwesome';
import logo from '../assets/logo.png';
import {cwPost} from '../utils/http';
const resetAction = StackActions.reset({
  index: 0,
  actions: [NavigationActions.navigate({routeName: 'main'})],
});

const accountInput = React.createRef();
const passwordInput = React.createRef();
export default class LoginPage extends Component {
  constructor(props) {
    super(props);
    global.navigation = this.props.navigation;
    this.state = {
      account: '',
      password: '',
      checked: false,
    };

    // storage.load({
    //     key: 'token'
    // }).then(res => {
    //     console.log('token啊', res);
    // })
    storage
      .load({
        key: 'account',
      })
      .then(account => {
        console.log(account);
        this.setState({
          account,
        });
      });

    storage
      .load({
        key: 'remmber',
      })
      .then(remmber => {
        this.setState({
          checked: remmber,
        });
        if (remmber) {
          storage
            .load({
              key: 'password',
            })
            .then(password => {
              console.log('pass', password);
              this.setState({
                password,
              });
            });
        }
        storage
          .load({
            key: 'token',
          })
          .then(token => {
            console.log('token', token);
            if (remmber && token) {
              // this.props.navigation.dispatch(resetAction);
              this.toLogin();
            }
          });
      });
  }

  changeLogin(text, field) {
    if (field === 'account') {
      this.setState({account: text});
    } else {
      this.setState({password: text});
    }
  }

  toLogin() {
    const {account, password, checked} = this.state;
    console.log(account, password);
    const params = {
      account,
      password,
    };
    cwPost('Authority/Login', params).then(data => {
      console.log('login', data);
      const {token, user} = data;
      storage.save({key: 'token', data: token});
      storage.save({key: 'user', data: user});
      storage.save({key: 'remmber', data: checked});
      storage.save({key: 'account', data: account});
      if (checked) {
        storage.save({key: 'password', data: password});
      }
      this.props.navigation.dispatch(resetAction);
    });
  }

  componentDidMount() {
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackHandler);
    }
    // this.keyboardWillShowSub = Keyboard.addListener('keyboardDidShow', () => this.keyboardWillShow());
    this.keyboardWillHideSub = Keyboard.addListener('keyboardDidHide', () =>
      this.keyboardWillHide(),
    );
  }

  //移除
  componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackHandler);
    }
    // this.keyboardWillShowSub.remove();
    this.keyboardWillHideSub.remove();
  }

  keyboardWillHide() {
    if (accountInput.current.isFocused()) {
      accountInput.current.blur();
    }
    if (passwordInput.current.isFocused()) {
      passwordInput.current.blur();
    }
  }

  onBackHandler = () => {
    if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
      //最近2秒内按过back键，可以退出应用。
      BackHandler.exitApp();
      return false;
    }
    this.lastBackPressed = Date.now();
    ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
    return true; //默认行为
  };

  render() {
    const {account, password} = this.state;
    return (
      <View>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView style={styles.loginPadding}>
            <View
              style={{
                flex: 1,
                alignItems: 'center',
                justifyContent: 'center',
                marginBottom: 20,
              }}>
              <Image source={logo} />
            </View>
            <View style={(styles.mb, {flexDirection: 'column'})}>
              <Input
                value={account}
                ref={accountInput}
                labelStyle={{fontSize: 14}}
                placeholder="请输入用户名"
                onChange={e => {
                  this.changeLogin(e.nativeEvent.text, 'account');
                }}
                leftIcon={
                  <Icon
                    name="user-o"
                    size={18}
                    color="#cecece"
                    style={{marginRight: 10}}
                  />
                }
              />
            </View>
            <View style={styles.mb}>
              <Input
                defaultValue={password}
                labelStyle={{fontSize: 14}}
                placeholder="请输入密码"
                ref={passwordInput}
                secureTextEntry={true}
                onChange={e => {
                  this.changeLogin(e.nativeEvent.text, 'password');
                }}
                leftIcon={
                  <Icon
                    name="eye-slash"
                    size={18}
                    color="#cecece"
                    style={{marginRight: 10}}
                  />
                }
              />
            </View>
            <CheckBox
              containerStyle={{backgroundColor: '#fff', borderColor: '#fff'}}
              title="记住密码"
              checked={this.state.checked}
              onPress={() => this.setState({checked: !this.state.checked})}
            />
            <View style={{marginTop: 0, padding: 10}}>
              <Button
                title="登       录"
                onPress={() => {
                  this.toLogin();
                }}
              />
            </View>
          </ScrollView>
        </SafeAreaView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  loginPadding: {
    padding: 30,
    marginTop: 80,
  },
  mb: {
    marginBottom: 5,
  },
});
